package com.wjyxsy.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

    public static BlockingDeque<Long> queue1 = new LinkedBlockingDeque<>(100);
    public static BlockingDeque<Long> queue2 = new LinkedBlockingDeque<>(100);
    public static BlockingDeque<Long> queue3 = new LinkedBlockingDeque<>(100);

    public final static int MAX_SIZE = 100;

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        long start = System.currentTimeMillis();

        Result invoke = invoker.invoke(invocation);

        long end = System.currentTimeMillis();

        Long timeEntity = end - start;
        if (invocation.getMethodName().equals("sayHello1")) {
            while (queue1.size() >= MAX_SIZE) {
                queue1.poll();
            }
            queue1.offer(timeEntity);
        } else if (invocation.getMethodName().equals("sayHello2")) {
            while (queue2.size() >= MAX_SIZE) {
                queue2.poll();
            }
            queue2.offer(timeEntity);

        } else if (invocation.getMethodName().equals("sayHello3")) {
            while (queue3.size() >= MAX_SIZE) {
                queue3.poll();
            }
            queue3.offer(timeEntity);
        }

        return invoke;
    }
}
